package com.yuke.cloud.service.tmc.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;

@Slf4j
@Service
public class BackUpDataBaseManager {
    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;
    @Value("${spring.datasource.url}")
    private String url;
    @Value("${spring.datasource.username}")
    private String userName;
    @Value("${spring.datasource.password}")
    private String password;
    @Value("${sqlbackup.path}")
    private String sqlPath;

    /**
     * 获取数据库名
     */
    public String getDataBaseName() {
        return url.substring(url.indexOf("3306"), url.indexOf("?")).replaceAll("/", "").replaceAll("3306", "");
    }

    /**
     * 获取主机地址
     */
    private String getHost() {
        return url.substring(url.indexOf("mysql"), url.indexOf("3306")).replace(":", "").replace("//", "").replace("mysql", "");
    }

    /**
     * 导出 sql 并返回相关信息
     */
    public void exportSql(String time) {
        // 指定导出的 sql 存放的文件夹
        File saveFile = new File(sqlPath);
        if (!saveFile.exists()) {
            saveFile.mkdirs();
        }

        String host = getHost();
        String dataBaseName = getDataBaseName();
        String fileName = time + "_" + "cloudpm.sql";

        StringBuilder sb = new StringBuilder();
        // 拼接备份命令
        sb.append("docker exec  yuke-mysql  ");
        sb.append(" mysqldump").append(" --opt").append(" -h ").append(host).append(" --user=").append(userName).append(" --password=").append(password);
        sb.append(" --result-file=").append(sqlPath + fileName).append(" --default-character-set=utf8 ").append(dataBaseName);

        String linux = "/bin/sh,-c,";
        String windows = "cmd /c ";
        String cmd= "";
        String os =System.getProperty("os.name");
        System.out.println("当前操作系统名称;"+os);
        if (os.toLowerCase().startsWith("win")){
            cmd = windows;
        }else if(os.toLowerCase().startsWith("Mac OS")){
            cmd = linux;
        }
        else if (os.toLowerCase().indexOf("linux") >= 0){
            cmd = linux;
        }
        else{
            cmd = windows;
        }

        try {
            Process exec = Runtime.getRuntime().exec(cmd +sb.toString());
            if (exec.waitFor() == 0) {
                log.info("数据库备份成功，保存路径：" + sqlPath);
            } else {
                System.out.println("cmd /c "+sb.toString());
                System.out.println("process.waitFor()=" + exec.waitFor());
            }
        } catch (IOException e) {
            log.error("备份 数据库 出现 IO异常 ", e);
        } catch (InterruptedException e) {
            log.error("备份 数据库 出现 线程中断异常 ", e);
        } catch (Exception e) {
            log.error("备份 数据库 出现 其他异常 ", e);
        }
    }

    /**
     * 导出 sql 并返回相关信息
     */
    public void backup(String time) throws IOException{
        String host = getHost();
        String dataBaseName = getDataBaseName();
        String fileName = time + "_" + "cloudpm.sql";

        Runtime runtime = Runtime.getRuntime();
        //-u后面是用户名，-p是密码-p后面最好不要有空格，-family是数据库的名字
        String cmd = "mysqldump  -u userName -ppassword --set-charset=UTF8 databaseName";
        StringBuilder sb = new StringBuilder();
        // 拼接备份命令
        sb.append("docker exec  yuke-mysql");
        sb.append("mysqldump").append(" --opt").append(" -h ").append(host).append(" --user=").append(userName).append(" --password=").append(password);
        sb.append(" --default-character-set=utf8 ").append(dataBaseName);
        System.out.println("拼接备份命令"+ cmd);
        Process process = runtime.exec(cmd);
        InputStream inputStream = process.getInputStream();
        InputStreamReader reader = new InputStreamReader(inputStream,"utf-8");
        BufferedReader br = new BufferedReader(reader);
        String s = null;
        StringBuffer sbb = new StringBuffer();
        while((s = br.readLine()) != null){
            sbb.append(s+"\r\n");
        }
        s = sbb.toString();
        File file = new File(sqlPath+fileName);
        file.getParentFile().mkdirs();
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(s.getBytes());
        fileOutputStream.close();
        br.close();
        reader.close();
        inputStream.close();
    }

    /**
     * 恢复到数据库
     */
    public void recover(String path) throws IOException {
        String dataBaseName = getDataBaseName();
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec("cmd /c mysql  -u "+ userName + "  -p "+ password + "  --default-character-set=utf8 "+dataBaseName);
        OutputStream outputStream = process.getOutputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
        String str = null;
        StringBuffer sb = new StringBuffer();
        while((str = br.readLine()) != null){
            sb.append(str+"\r\n");
        }
        str = sb.toString();
        System.out.println(str);
        OutputStreamWriter writer = new OutputStreamWriter(outputStream,"utf-8");
        writer.write(str);
        writer.flush();
        outputStream.close();
        br.close();
        writer.close();

    }
}
